package com.iceflame.zxingane.funs;

import java.util.Collection;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;

import com.adobe.fre.FREArray;
import com.adobe.fre.FREContext;
import com.adobe.fre.FREFunction;
import com.adobe.fre.FREObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.iceflame.zxingane.EventType;
import com.iceflame.zxingane.ZXingAne;

public class Decode implements FREFunction {

	@Override
	public FREObject call(FREContext arg0, FREObject[] arg1) {
		if(arg1.length == 0){
			return null;
		}
		ZXingAne.dispatchEvent(EventType.DEBUG, "StartDecode");
		long time = System.currentTimeMillis();
		try{
			int width = arg1[0].getAsInt();
			int height = arg1[1].getAsInt();
			int[] pixels = new int[width * height];
			
			FREArray array = (FREArray)arg1[2];
			long len = array.getLength();
			for(int i = 0 ; i < len ; i++){
				pixels[i] = array.getObjectAt(i).getAsInt();
			}
			Map<DecodeHintType,Object> hints = new HashMap<DecodeHintType, Object>();
			Collection<BarcodeFormat> decodeFormats = EnumSet.noneOf(BarcodeFormat.class);
			decodeFormats.addAll(EnumSet.of(BarcodeFormat.QR_CODE));
			hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);
			hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
			RGBLuminanceSource rgbsource = new RGBLuminanceSource(width, height, pixels);
			HybridBinarizer hybrid = new HybridBinarizer(rgbsource);
			BinaryBitmap binBitmap = new BinaryBitmap(hybrid);
			Result lResult = new MultiFormatReader().decode(binBitmap, hints);
			String str = lResult.getText();
			long timeUse = System.currentTimeMillis() - time;
			ZXingAne.dispatchEvent(EventType.DEBUG, "DecodeComplete,Use:" + timeUse);
			return FREObject.newObject(str);
		}catch(Exception e){
			String errStr = e.getMessage();
	        ZXingAne.dispatchEvent(EventType.ERROR, "DecodeCatchError:" + errStr);
	        return null;
		}
	}

}
